package com.vita.common;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;

public class PojoUtils {
    public static <O> O getObjectList(Class<O> clazz, String[] rowNos) throws Exception {
        //创建对象实例
        Object object = clazz.newInstance();
        //获取类声明的属性
        Field[] fields = clazz.getDeclaredFields();
        StringBuffer buffer = null;
        int size = Math.min(rowNos.length, fields.length);
        for (int j = 0; j < size; j++) {

            //获取属性的名字
            String fieldName = fields[j].getName();

            //如果获取参数值为空则继续循环
            String value = rowNos[j];
            if (value == null) {
                continue;
            }

            //参数值
            Object[] paramValue = new Object[1];
            if (fields[j].getType().toString().equals("class java.lang.String")) {
                paramValue[0] = value;
            }
            if (fields[j].getType().toString().equals("class java.lang.Integer")) {
                paramValue[0] = new Integer(value);
            }
            if (fields[j].getType().toString().equals("class java.lang.Double")) {
                paramValue[0] = new Double(value);
            }
            if (fields[j].getType().toString().equals("class java.util.Date")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                paramValue[0] = sdf.parse(value);
            }

            //参数类型
            Class[] paramType = {fields[j].getType()};

            //得到set方法的名字
            buffer = new StringBuffer("set");
            buffer.append(fieldName.substring(0, 1).toUpperCase());
            buffer.append(fieldName.substring(1));
            //获取放回
            Method method = clazz.getDeclaredMethod(buffer.toString(), paramType);
            //执行方法
            method.invoke(object, paramValue);
        }

        return (O) object;
    }
}
